package com.moodykettle.unittests.file.xml;

import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XmlSAXParser extends DefaultHandler {

	public Vector<Employee> myEmpls = new Vector<Employee>();
	Employee tempEmp = new Employee();
	public String tempVal;
	
	public void parseDocument(String file) {

		//get a factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try 
		{

			//get a new instance of parser
			SAXParser sp = spf.newSAXParser();

			//parse the file and also register this class for call backs
			sp.parse(file, this);

		}
		catch(SAXException se) 
		{
			se.printStackTrace();
		}
		catch(ParserConfigurationException pce) 
		{
			pce.printStackTrace();
		}
		catch (IOException ie) 
		{
			ie.printStackTrace();
		}
	}
	
	/**
	 * Iterate through the list and print
	 * the contents
	 */
	public void printData()
	{
		
		System.out.println("No of Employees '" + myEmpls.size() + "'.");
		
		Iterator<Employee> it = myEmpls.iterator();
		while(it.hasNext()) {
			System.out.println(it.next().toString());
		}
	}
	
	//Event Handlers
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		//reset
		tempVal = "";
		if(qName.equalsIgnoreCase("Employee")) {
			//create a new instance of employee
			tempEmp = new Employee();
			tempEmp.setType(attributes.getValue("type"));
		}
	}

	public void endElement(String uri, String localName, String qName) throws SAXException {

		if(qName.equalsIgnoreCase("Employee")) {
			//add it to the list
			myEmpls.add(tempEmp);
			
		}else if (qName.equalsIgnoreCase("Name")) {
			tempEmp.setName(tempVal);
		}else if (qName.equalsIgnoreCase("Id")) {
			tempEmp.setId(Integer.parseInt(tempVal));
		}else if (qName.equalsIgnoreCase("Age")) {
			tempEmp.setAge(Integer.parseInt(tempVal));
		}
		
	}
	
	public void characters(char[] ch, int start, int length) throws SAXException {
		tempVal = new String(ch,start,length);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try
		{
			XmlSAXParser xml = new XmlSAXParser();
	
			Scanner sc = new Scanner(System.in);
			System.out.println("Input xml file: ");
			String file = sc.nextLine();
			
			xml.parseDocument(file);
			xml.printData();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

}
